<?php

/* 订单 returns */
class ReturnsModel extends BaseModel
{
    var $table  = 'returns';
    var $prikey = 'returns_id';
    var $_name  = 'returns';
    var $_relation  = array(
        // 一个退货退款有多个退货退款日志
        'has_returnslog' => array(
            'model'         => 'returnslog',
            'type'          => HAS_MANY,
            'foreign_key'   => 'returns_id',
            'dependent'     => true
        ),
        'belongs_to_order'  => array(
            'type'          => BELONGS_TO,
            'reverse'       => 'has_returns',
            'model'         => 'order',
        ),
        'belongs_to_orderextm'  => array(
            'type'          => BELONGS_TO,
            'reverse'       => 'has_returns',
            'model'         => 'orderextm',
        ),
        'belongs_to_ordergoods'  => array(
            'type'          => BELONGS_TO,
            'reverse'       => 'has_returns',
            'model'         => 'ordergoods',
        ),
        'has_returnsshippingfee' => array(
            'model'         => 'returnsshippingfee',
            'type'          => HAS_ONE,
            'foreign_key'   => 'returns_id',
            'dependent'     => true
        ),
    );
    
    /**
     *    关闭退货退款申请
     *
     *    @author    yanghj 2014.8.12
     *    @param     $order_id    订单ID
     *    @param     $close_type  关闭退货退款类型 1.买家确认订单 2.卖家发货 3.万菱介入 4.操作超时
     *    @param     $shipping_name  物流公司  $close_type 等于2.卖家发货 才要传参数
     *    @param     $shipping_sn    物流单号  $close_type 等于2.卖家发货 才要传参数
     *    @param     $returns_id     退货退款ID 3.万菱介入 才要传参数
     *    @return    boole
     */
    function close_returns($order_id, $close_type = 1, $shipping_name = '', $shipping_sn = '', $returns_id = 0)
    {
        $returns_log_mod =& m('returnslog');
        $conditions = '';
        if($close_type == 1)
        {
            $conditions = " order_id = {$order_id} AND status IN(1,4,6)";
            $returns = $this->find(array(
    		'fields'        => "returns_id,type,seller_id,buyer_id,returns_seller_name,returns_buyer_name",
    		'conditions'    => $conditions,
		    ));
            
            if($returns)
            {
                $first = reset($returns);
                $edit_data = array(
    			'status'        => -1,
                'close_type'    => 1,
    			'confirm_time'  => time(),
    			'finished_time' => time(),		
    			);
                
                /*修改退货退款状态*/
                $this->edit($conditions, $edit_data);
                if ($this->has_error())
        		{        		
        			return $this->get_error();
        		}
                
                foreach($returns as $key => $val)
                {
                    $log_data[] = array(
        			'returns_id' => $val['returns_id'],
        			'operator'   => $val['returns_buyer_name'],
        			'remark'     => '买家确认订单,申请关闭',
                    'log_time'   => time(),
        			);
                    $this->send_returns_email($val['buyer_id'],$val['returns_id'],8);//发送邮件                                    
                }
                 /*添加到退货退款日志表*/
                if (!($returns_log_mod->add($log_data)))
                {                        
                    return $returns_log_mod->get_error();
                }                
            }
            
        }
        
        if($close_type == 2)
        {
            $conditions = " order_id = {$order_id} AND status IN(1,4,6) AND type =1 ";
            $returns = $this->find(array(
    		'fields'        => "returns_id,type,seller_id,buyer_id,returns_seller_name,returns_buyer_name",
    		'conditions'    => $conditions,
		    ));
            
            if($returns)
            {
                $first = reset($returns);
                $edit_data = array(
    			'status'        => -1,
                'close_type'    => 2,
    			'confirm_time'  => time(),
    			'finished_time' => time(),		
    			);
                
                /*修改退货退款状态*/
                $this->edit($conditions, $edit_data);
                if ($this->has_error())
        		{        		
        			return $this->get_error();
        		}
                
                foreach($returns as $key => $val)
                {
                    $log_data[] = array(
        			'returns_id' => $val['returns_id'],
        			'operator'   => $val['returns_seller_name'],
        			'remark'     => '卖家已发货，物流公司：'.$shipping_name.'，物流单号：'.$shipping_sn.'。',
                    'log_time'   => time(),
        			);
                    $this->send_returns_email($val['buyer_id'],$val['returns_id'],4);//发送邮件                                       
                }
                
                /*添加到退货退款日志表*/
                if (!($returns_log_mod->add($log_data)))
                {                        
                    return $returns_log_mod->get_error();
                }                
            }
            
        }
        
        if($close_type == 3)
        {          
            if($returns_id > 0)
            {
                $user_id = $this->get_fields_name($returns_id,'buyer_id');
                $edit_data = array(
    			'status'        => -1,
                'close_type'    => 3,
    			'confirm_time'  => time(),
    			'finished_time' => time(),		
    			);
                
                /*修改退货退款状态*/
                $this->edit($returns_id, $edit_data);
                if ($this->has_error())
        		{        		
        			return $this->get_error();
        		}               
                
                $log_data = array(
    			'returns_id' => $returns_id,
    			'operator'   => '万菱客服',
    			'remark'     => '万菱介入,申请关闭',
                'log_time'   => time(),
    			);
                
                /*添加到退货退款日志表*/
                if (!($returns_log_mod->add($log_data)))
                {                        
                    return $returns_log_mod->get_error();
                }
                
                $this->send_returns_email($user_id,$returns_id,8);//发送邮件                    
                              
            }
            
        }
                
       return true;
    }
    
    /**
     *    退货退款申请过程发送的邮件
     *
     *    @author    yanghj 2014.8.19
     *    @param     $user_id    发送邮件到哪个会员的ID
     *    @param     $returns_id 退货退款ID 
     *    @return    boole
     */
    function send_returns_email($user_id,$returns_id,$send_type = 1)
    {
        
        if(intval($user_id)<1 || intval($returns_id)<1)
        {
            return false;
        }
          
        $model_usersafety = & m('usersafety');
		$user_info     = $model_usersafety->get("user_id='{$user_id}'");
		$email    = $user_info['binding_email'];
        $returns_type = array(
            '1' => '退款',
            '2' => '退货退款',
            '3' => '换货',
        );
		if(!$email)
		{
		   return false; 
		}
        
        $returns_info = $this->get(array(
		'fields'        => "returns_sn,type,close_type,seller_id,buyer_id,returns_seller_name,returns_buyer_name,status,goods_amount,shipping_fee,ordergoods.goods_name",
		'conditions'    => "returns_id={$returns_id}",
		'join'          => 'belongs_to_ordergoods',
		));
        
        if(!$returns_info)
        {
           return false; 
        }
        switch ($send_type)
        {
            case '1': //买家申请退货退款时的通知
                $mail_tpl = 'toseller_returns_apply';             
                break;
            case '2': //买家修改申请退货退款时的通知
                $mail_tpl = 'toseller_returns_edit';           
                break;
            case '3': //买家退货时的通知
                $mail_tpl = 'toseller_returns_shipments';    
                break;
            case '4': //买家申请退款卖家发货时的通知
                $mail_tpl = 'tobuyer_returns_sipping';              
                break;
            case '5': //卖家拒绝退货退款申时的通知
                $mail_tpl = 'tobuyer_returns_refuse';              
                break;
            case '6': //卖家同意退货退款申时的通知
                $mail_tpl = 'tobuyer_returns_agree';              
                break;
            case '7': //申时退货退款成功时的通知
                $mail_tpl = 'tobuyer_returns_succeed';              
                break; 
            case '8': //申时退货退款关闭时的通知
                $mail_tpl = 'tobuyer_returns_close';              
                break;                      
            default:
                $mail_tpl = 'toseller_returns_apply'; //默认买家申请退货退款时的通知
                break;    
            
        }
        $returns_info['seller_name'] = $returns_info['returns_seller_name'];
        $returns_info['buyer_name'] = $returns_info['returns_buyer_name'];
        $returns_info['type'] = $returns_type[$returns_info['type']];
		$mail_info = get_mail($mail_tpl, array('returns' => $returns_info));
        if(!$mail_info)
        {
            return false; 
        }
        $model_mailqueue =& m('mailqueue');
        $mails = array(
            'mail_to'       => $email,
            'mail_encoding' => CHARSET,
            'mail_subject'  => addslashes($mail_info['subject']),
            'mail_body'     => addslashes($mail_info['message']),
            'priority'      => MAIL_PRIORITY_LOW,
            'add_time'      => gmtime(),
        );
		$model_mailqueue->add($mails);
               
       return true;
    }

    /**
     *   某个订单退货退款申请情况
     *
     *    @author    yanghj 2015.01.29
     *    @param     $order_id    订单ID
     *    @return    boole
     */
    function order_returns($order_id)
    {
        $arr = array('returns_case'=>1,'message'=>'订单商品没有退款');
        $order_goods_mod =& m('ordergoods');
        $order_goods_sum = $order_goods_mod->getOne("SELECT SUM(quantity) FROM  {$order_goods_mod->table} WHERE  order_id ={$order_id} ");
        $returns_goods_sum = $this->getOne("SELECT SUM(quantity) FROM  {$this->table} WHERE  order_id ={$order_id} AND status IN(1,3,4,5,6,7,8)");
        $returns_affirm_sum = $this->getOne("SELECT SUM(quantity) FROM  {$this->table} WHERE  order_id ={$order_id} AND status IN(7,8)");
        if(intval($returns_goods_sum) > 0)
        {
            if(intval($order_goods_sum) == intval($returns_affirm_sum))
            {
                $arr['returns_case'] = 3;
                $arr['message'] = '订单商品全额退款,不用发货';
            }
            else
            {
                $arr['returns_case'] = 2;
                $arr['message'] = '订单部分商品有退款';
            }
        }

        return $arr;
    }
    
}

?>
